import requests
import random
import netifaces
import json
import re
import base64

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36',
}

address = 'http://192.168.200.2:801/eportal/'

response_pattern=re.compile('([a-zA-Z0-9]+)\((.*)\)')

class CQUPTDrcom:
    def __init__(self, name, pw, ip=None, method='cmcc', phone=False) -> None:
        '''
        name:   你的用户名
        pw:     你的登陆账号密码
        ip:     电脑直接连接到校园网的时候, 可以不填.
                如果是作为脚本挂在路由器上的, 也可以不填.
                只有客户端跨过路由器连接到校园网时, 才需要手动指定.
        method: 电信对应telecom, 移动对应cmcc, 教师或临时对应xyw
        phone:  模拟手机连接时请填写True, 模拟电脑连接时填写False
        '''
        self.name = name
        self.pw = pw
        self.method = method # cmcc telecom xyw
        self.phone=phone
        if not ip:
            self.detect_ip()
        else:
            self.ip = ip
    
    def login(self):
        params = {
            'c':'Portal',
            'a':'login',
            'callback':'dr1003',
            'login_method':'1',
            'user_account':',%d,%s@%s' % (int(self.phone), self.name, self.method),
            'user_password':self.pw,
            'wlan_user_ip':self.ip,
            'wlan_user_ipv6':'',
            'wlan_user_mac':'000000000000',
            'wlan_ac_ip':'',
            'wlan_ac_name':'',
            'jsVersion':'3.3.3',
            'v':int(random.random()*10000),
        }
        res = requests.get(address, params=params, headers=headers)
        res_regex = response_pattern.split(res.text)

        if len(res_regex) != 4:
            print(' - 返回值有误!')
            return None

        else:
            json_res = json.loads(res_regex[2])
            # print(json_res)
            if json_res['result'] == '1':
                print(' - 登陆成功.')
                return 0
            else:
                print(' ! 登陆失败, 网页提供的信息是: ',json_res['msg'])
                # print(' - 目前已知会造成这类问题的原因有: 重复登陆, 账号占用')
                return 1


    def logout(self):
        params = {
            'c':'Portal',
            'a':'logout',
            'callback':'dr1003',
            'login_method':'1',
            'user_account':'drcom',
            'user_password':'123',
            'ac_logout':'1',
            'register_mode':'1',
            'wlan_user_ip':self.ip,
            'wlan_user_ipv6':'',
            'wlan_vlan_id':'1',
            'wlan_user_mac':'000000000000',
            'wlan_ac_ip':'',
            'wlan_ac_name':'',
            'jsVersion':'3.3.3',
            'v':int(random.random()*10000),
        }
        res = requests.get(address, params=params, headers=headers)
        print(res.text)
        res_regex = response_pattern.split(res.text)

        if len(res_regex) != 4:
            print(' - 返回值有误!')
            return

        else:
            json_res = json.loads(res_regex[2])
            # print(json_res)
            if json_res['result'] == '1':
                print(' - 注销成功.')
                return 0
            else:
                print(' ! 注销失败, 网页提供的信息是: ',json_res['msg'])
                # print(' - 目前已知会造成这类问题的原因有: 反复注销')
                return 1

    def detect_ip(self):
        routingGateway = netifaces.gateways()['default'][netifaces.AF_INET][0]
        routingNicName = netifaces.gateways()['default'][netifaces.AF_INET][1]

        for interface in netifaces.interfaces():
            if interface == routingNicName:
                # print netifaces.ifaddresses(interface)
                routingNicMacAddr = netifaces.ifaddresses(interface)[netifaces.AF_LINK][0]['addr']
                try:
                    routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
                    # TODO(Guodong Ding) Note: On Windows, netmask maybe give a wrong result in 'netifaces' module.
                    routingIPNetmask = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['netmask']
                except KeyError:
                    pass

        
        print(" - 网关:", routingGateway)
        print(" - 本机MAC:", routingNicMacAddr)
        print(" - 本机IP:", routingIPAddr)
        print(" - 子网掩码:", routingIPNetmask)
        print(" ! 自动检测的IP不适用于路由器, 使用路由器时请改用其他方式获取路由器的IP!")
        self.ip = routingIPAddr
        return self.ip